package cn.wolfcode.wolf2w.redis.service.impl;

import cn.wolfcode.wolf2w.domain.Strategy;
import cn.wolfcode.wolf2w.domain.StrategyFavors;
import cn.wolfcode.wolf2w.redis.service.IStrategyStratisVoRedisService;
import cn.wolfcode.wolf2w.redis.util.RedisKeys;
import cn.wolfcode.wolf2w.redis.vo.StrategyStatisVo;
import cn.wolfcode.wolf2w.service.IStrategyFavorsService;
import cn.wolfcode.wolf2w.service.IStrategyService;
import cn.wolfcode.wolf2w.util.DateUtil;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class StrategyStratisVoRedisServiceImpl implements IStrategyStratisVoRedisService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private IStrategyService strategyService;

    @Autowired
    private IStrategyFavorsService strategyFavorsService;

    @Override
    public StrategyStatisVo getStrategyStatisVo(String sid) {
        // 拼接vo对象的key
        String key = RedisKeys.STRATEGY_STATIS_VO.join(sid);

        // 判断key是否存在
        StrategyStatisVo vo = null;
        if (redisTemplate.hasKey(key)){
            // 存在，已经初始化好了，通过key去获取value
            vo = JSON.parseObject(redisTemplate.opsForValue().get(key),StrategyStatisVo.class);
        }else {
            // 不存在，需要初始化从数据库中获取值到redis中
            Strategy strategy = strategyService.get(sid);
            vo = new StrategyStatisVo();
            BeanUtils.copyProperties(strategy,vo);
            vo.setStrategyId(sid);
            // 缓存到redis中
            redisTemplate.opsForValue().set(key, JSON.toJSONString(vo));
        }
        return vo;
    }

    @Override
    public void setStrategyStatisVo(StrategyStatisVo vo) {
        // 拼接vo对象的key
        String key = RedisKeys.STRATEGY_STATIS_VO.join(vo.getStrategyId());
        redisTemplate.opsForValue().set(key, JSON.toJSONString(vo));
    }

    @Override
    public void viewnumIncrease(String sid,int num) {
        // 拼接vo对象的key
       // String key = RedisKeys.STRATEGY_STATIS_VO.join(sid);

        StrategyStatisVo vo = this.getStrategyStatisVo(sid);
        vo.setViewnum(vo.getViewnum() + num);
        // 缓存到redis中
        //redisTemplate.opsForValue().set(key, JSON.toJSONString(vo));
        this.setStrategyStatisVo(vo);
    }

    @Override
    public void replynumIncrease(String strategyId, int num) {
        StrategyStatisVo vo = this.getStrategyStatisVo(strategyId);
        vo.setReplynum(vo.getReplynum() + num);
        this.setStrategyStatisVo(vo);
    }

    @Override
    public boolean favornumIncrease(String sid,String uid) {
        // 拼接用户收藏集合 key
        String strKey = RedisKeys.USER_STRATEGY_FAVOR.join(uid);
        // 判断key是否存在，存在获取，不存在，最初list集合不存在的，需要初始化一个空的list
        List<String> sidList = new ArrayList<>();
        if (redisTemplate.hasKey(strKey)){
            String value = redisTemplate.opsForValue().get(strKey);
            sidList = JSON.parseArray(value,String.class);
        }else {
            // 不存在，从数据库中获取，保存到redis中
            StrategyFavors strategyFavors = strategyFavorsService.queryByUsid(uid);
            if (strategyFavors != null){
                sidList = strategyFavors.getFavors();
                redisTemplate.opsForValue().set(strKey,JSON.toJSONString(sidList));
            }
        }
        // 判断传入的攻略id是否存在list，存在（取消），不存在（收藏）
        StrategyStatisVo vo = this.getStrategyStatisVo(sid);
        if (sidList.contains(sid)){
            // 存在（取消收藏），收藏数+1，将攻略id加入list
            vo.setFavornum(vo.getFavornum() - 1);
            sidList.remove(sid);
        }else {
            // 不存在（收藏）
            vo.setFavornum(vo.getFavornum() + 1);
            sidList.add(sid);
        }

        // 更新vo和用户收藏集合list
        this.setStrategyStatisVo(vo);
        redisTemplate.opsForValue().set(strKey,JSON.toJSONString(sidList));

        return sidList.contains(sid);  // 存在，true；不存在，false
    }

    @Override
    public boolean thumbupnumIncrease(String sid, String id) {
        // 拼接key (某用户点赞某一篇的攻略)
        String key = RedisKeys.USER_STRATEGY_THUMBUP.join(id, sid);

        // 判断是否存在key，存在，不做处理，返回false；不存在，创建并设置过期时间，点赞数+1
        if (!redisTemplate.hasKey(key)){
            // 过期时间
            Date endDate = DateUtil.getEndDate(new Date());
            long time = DateUtil.getDateBetween(new Date(), endDate);
            redisTemplate.opsForValue().set(key,"1",time, TimeUnit.SECONDS);

            StrategyStatisVo vo = this.getStrategyStatisVo(sid);
            vo.setThumbsupnum(vo.getThumbsupnum() + 1);
            this.setStrategyStatisVo(vo);
            return true;
        }
        return false;
    }
}
